package com.mspbots.attendance.trigger;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mspbots.api.client.CoreClient;
import com.mspbots.attendance.controller.TenantAttendanceController;
import com.mspbots.attendance.model.TenantAttendance;
import com.mspbots.attendance.model.TriggerEventDTO;
import com.mspbots.attendance.service.TenantAttendanceService;
import com.mspbots.attendance.request.TenantDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

import static com.mspbots.common.TriggerEvent.ATTENDANCE_AUTO;

/**
 * @author Dinnes Zhang
 * @date
 */
@Slf4j
@Component
public class LunchAndBreakTriggerEvent {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitMessagingTemplate messagingTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private CoreClient coreClient;

    @Autowired
    private TenantAttendanceService service;

    private static final String REDIS_KEY_PREFIX_TENANT = "MSPBOTS:CONFIG:TENANT:";

//    @Scheduled(initialDelay = 10000, fixedRate = 60 * 1000)
    @Scheduled(initialDelay = 10000, fixedRateString = "${mspbots.fixedDelay.lunchAndBreak}")
    public void produce() {
        log.debug("attendance auto...");
        List tenants = redisTemplate.opsForList().range(REDIS_KEY_PREFIX_TENANT + "tenants", 0, -1);
        log.debug("tenants ...  {}", tenants);
        List<TenantDTO> tenantDTOS = objectMapper.convertValue(tenants, new TypeReference<List<TenantDTO>>() {
        });
        log.debug("tenantDTOS ...  {}", tenantDTOS);
        tenantDTOS.stream().filter(item -> item.getStatusId() == 1).forEach(tenantDTO ->
                service.findSubAction(tenantDTO.getId()).parallelStream().forEach(subAction -> {
                    TenantAttendanceController.TenantAttendanceParams attendanceParams = new TenantAttendanceController.TenantAttendanceParams();
                    attendanceParams.setTenantId(subAction.getTenantId());
                    attendanceParams.setUserId(subAction.getUserId());
                    attendanceParams.setSubAction("back");
                    attendanceParams.setCreateTimeStart(subAction.getLogTime());
                    attendanceParams.setCreateTimeEnd(LocalDateTime.now());
                    TenantAttendance back = service.findAction(attendanceParams);
                    if (StringUtils.isEmpty(back) && !StringUtils.isEmpty(subAction.getTeamsUserId())) {
                        try {
                            JsonNode payload = this.objectMapper.readTree(this.objectMapper.writeValueAsString(subAction));
                            if (payload != null) {
                                TriggerEventDTO triggerEventDTO = new TriggerEventDTO();
                                triggerEventDTO.setTenantId(subAction.getTenantId());
                                triggerEventDTO.setEventName(ATTENDANCE_AUTO.getEvent());
                                triggerEventDTO.setScope(ATTENDANCE_AUTO.getScope());
                                triggerEventDTO.setPayload(payload);
                                triggerEventDTO.setUserInfo(payload);
                                this.messagingTemplate.convertAndSend("msp.trigger.event", "", triggerEventDTO);
                                log.debug("cw msp.trigger.event Attendance Schedule:[{}] ", this.objectMapper.convertValue(triggerEventDTO, JsonNode.class));
                            }
                        } catch (JsonProcessingException e) {
                            e.printStackTrace();
                        }
                    }
                })
        );
    }
}
